package com.umfwechat.wx.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.util.PropertyUtil;
import com.umfwechat.common.constant.CacheConsts;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.constant.ConfigConsts;
import com.umfwechat.common.constant.MsgConsts;
import com.umfwechat.common.constant.ValueConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.util.DateTimesUtil;
import com.umfwechat.util.HttpUtil;
import com.umfwechat.util.RedisUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.ResultJsonUtil;
import com.umfwechat.util.SaasPropertyUtil;
import com.umfwechat.util.StringUtil;
import com.umfwechat.util.wx.MessageUtil;
import com.umfwechat.util.wx.SignUtil;
import com.umfwechat.wx.pojo.AccessTokenPojo;
import com.umfwechat.wx.resp.TextMessage;
import com.umfwechat.wx.service.WeixinService;
import com.umpay.sp.model.common.ReqMessage;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.model.saas.AppChannel;
import com.umpay.sp.model.saas.StoreInf;
import com.umpay.sp.service.saas.remote.AppChannelServiceRemote;
import com.umpay.sp.service.saas.remote.StoreInfServiceRemote;
import com.umpay.sp.service.sys.remote.UserServiceRemote;
import com.umpay.sp.xml.XmlData;

import net.sf.json.JSONObject;

/**
 * 接收微信 公众平台推送消息
 * @author Administrator
 *
 */
@Controller
public class WeChatController {
	
	private static Logger log = LoggerFactory.getLogger(WeChatController.class);
	@Autowired
	private WeixinService weixinService;

	@Resource
	private UserServiceRemote userServiceRemote_sp;
	//店铺部署详情列表接口
	@Resource
	private StoreInfServiceRemote storeInfServiceRemot;
	//渠道表接口，费率查询
	@Resource
	private AppChannelServiceRemote appChannelServiceRemote;

	/**
	 * 成为开发者
	 * 
	 * @param signature
	 *            微信加密签名
	 * @param timestamp
	 *            时间戳
	 * @param nonce
	 *            随机数
	 * @param echostr
	 *            随机字符串
	 * @throws Exception 
	 */
	@RequestMapping(value="/getDeveloper", method = { RequestMethod.GET, RequestMethod.POST })
	public void getDeveloper(HttpServletResponse response, HttpServletRequest request) throws Exception {
		System.out.println("进入微信请求的地址");
		boolean isGet = request.getMethod().toLowerCase().equals("get");  
		log.info("进入微信请求的地址======WeChatController===开始===getDeveloper====【isGet】"+isGet);
		
		// 响应消息
		PrintWriter out = response.getWriter();
		if(isGet){
			System.out.println("enter get");  
			log.info("进入微信请求的地址===enter get");
			// 调用核心业务类接收消息、处理消息
			// 微信加密签名
			String signature = request.getParameter("signature");
			// 时间戳
			String timestamp = request.getParameter("timestamp");
			// 随机数
			String nonce = request.getParameter("nonce");
			// 随机字符串
			String echostr = request.getParameter("echostr");
			
			// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
			if (SignUtil.checkSignature(signature, timestamp, nonce)) {
				out.print(echostr);
			}
			out.close();
			out = null;
		}else{
			System.out.println("enter post"); 
			log.info("进入微信请求的地址===enter post");
			 try {  
	             // 接收消息并返回消息  
				 out.print("success");
				 String string = this.processRequest(request);
				 log.info("进入微信请求的地址======WeChatController===结束===getDeveloper!!!!!!!&&&&&&&&&&客户返回给微信xml"+string);
				// out.print("success");
	            } catch (IOException e) {  
	                e.printStackTrace();  
	                out.print("success");
	            }finally {   
	                if(out!=null) {   
	                    out.flush();  
	                    out.close();  
	                } 
	             }
		}
		
	}
	/*
	 * 接收消息并返回消息 
	 */
	private String processRequest(HttpServletRequest request) throws Exception {
		String respMessage = null;

		// 默认返回的文本消息内容
		String respContent = "";
		// xml请求解析
		Map<Object, Object> requestMap = MessageUtil.parseXml(request);
		log.info("微信给url推送消息获取 ：requestMap=" + requestMap);
		// 发送方帐号（open_id）
		String fromUserName = requestMap.get("FromUserName").toString();
		// 公众帐号
		String toUserName = requestMap.get("ToUserName").toString();
		// 消息类型
		String msgType = requestMap.get("MsgType").toString();
		// 时间搓
		String createTime = requestMap.get("CreateTime").toString();
		// 回复文本消息
		TextMessage textMessage = new TextMessage();
		textMessage.setToUserName(fromUserName);
		textMessage.setFromUserName(toUserName);
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
		textMessage.setFuncFlag(0);

		// 文本消息
		if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
			respContent = "您发送的是文本消息！";
		}
		// 图片消息
		else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
			respContent = "您发送的是图片消息！";
		}
		// 地理位置消息
		else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
			respContent = "您发送的是地理位置消息！";
		}
		// 链接消息
		else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
			respContent = "您发送的是链接消息！";
		}
		// 音频消息
		else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
			respContent = "您发送的是音频消息！";
		}
		// 事件推送
		else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
			log.info("】【】【】【】】【】【】进入事件推送【】【】【】【】【】【】【");
			// 事件类型
			String eventType = requestMap.get("Event").toString();
			// 订阅
			if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)
					|| eventType.equals(MessageUtil.EVENT_TYPE_SCAN)) {
				
				String ticket=null;
				// 二维码的ticket
				if(requestMap.get("Ticket")!=null){
					ticket = requestMap.get("Ticket").toString();
				}
				if(StringUtil.isNotEmpty(ticket)){
					log.info("扫码事件!!!!!!!!!+===========进入++++====获取 ：ticket=" + ticket);
					//获取二维码场景值sceneId
					String eventKey = requestMap.get("EventKey").toString();
					//判断是否关注过
					//boolean b = eventKey.contains("qrscene");
					//if(b){//未关注
						int i = eventKey.indexOf("_");
						String sceneId = eventKey.substring(i + 1);
						log.info("扫码事件获取 ：sceneId=" + sceneId);
						//获取用户的详情信息、店铺信息、第三方网站信息、绑定第三方网站
						log.info("获取用户的详情信息、店铺信息、第三方网站信息、绑定第三方网站 ===++++++开始++++++==WeChatController===++++==scanQrcode=======");
						ResMessage resMessage = this.scanQrcode(sceneId,fromUserName);
						log.info("获取用户的详情信息、店铺信息、第三方网站信息、绑定第三方网站 ===++++++结束++++++==WeChatController===++++==scanQrcode=======");
						//判断是否绑定成功
						if(resMessage.getRetCode().equals(RetCode.SUCCESS)){
							log.info("绑定成功 ：resMessage=" + resMessage.getRetCode());
							String retMsg = resMessage.getRetMsg();
							//发送绑定客服消息
							weixinService.sendMessage(fromUserName,retMsg);
							sendSignTemplate(fromUserName, resMessage);//给收款人发送待签约模板消息
							respContent = "";
						}else{
							String retMsg="欢迎关注享云服务,您绑定失败,请重新扫码或联系客服！";
							weixinService.sendMessage(fromUserName,retMsg);
							respContent ="";
						}
				}else{
					log.info("关注事件=====进入========&&&&&&&&&&&&+++++++++++");
					log.info("关注事件+++++给对应角色打标签 ===++++++开始++++++==WeChatController===++++==attention=======");
					ResMessage resMessage = this.attention(fromUserName);
					log.info("关注事件+++++给对应角色打标签 ======++++++结束++++++==WeChatController===++++==attention=======");
					//判断是否绑定成功
					if(resMessage.getRetCode().equals(RetCode.SUCCESS)){
						log.info("绑定成功 ：resMessage=" + resMessage);
						String retMsg = resMessage.getRetMsg();
						//发送绑定客服消息
						weixinService.sendMessage(fromUserName,retMsg);
						sendSignTemplate(fromUserName, resMessage);//给收款人发送待签约模板消息
						respContent = "";
					}else{
						String retMsg="欢迎关注享云服务";
						weixinService.sendMessage(fromUserName,retMsg);
						respContent = "";
					}
				}
			}
			// 自定义菜单点击事件
			else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
				log.info("自定义菜单点击事件 ：fromUserName=" + fromUserName);
				respContent="";
			}
		}
		respContent="";
		textMessage.setContent(respContent);
		respMessage = MessageUtil.textMessageToXml(textMessage);
		return respMessage;
	}
	
	//关注事件
	public ResMessage attention(String fromUserName){
		
		ResMessage resMessage = new ResMessage();
		try {
			// 根据openid查询第三方网站用户的用户编号
			ReqMessage req1 = ReqMessageUtil.makeSpReq();
			req1.getReqMap().put("externaluserId", fromUserName);
			req1.getReqMap().put("state","2");
			log.info("查询第三方网站用户接口开始 【1】【1】【1】【1】：req1=" + req1);
			ResMessage res1 = userServiceRemote_sp.queryUserBind(req1);
			log.info("查询第三方网站用户接口结束【1】【1】【1】【1】 ：res1=" + res1);
			// 第三方网站查询失败
			if (!res1.getRetCode().equals(RetCode.SUCCESS)&&!res1.getRetCode().equals(RetCode.NO_DATA)) {
				log.info("查询第三方网站用户接口失败 :=" + res1.getRetMsg());
				return res1;
			}
			if(res1.getRetCode().equals(RetCode.NO_DATA)){
				
				//给无角色打标签
				log.info("给无角色打标签接口开始 ：fromUserName"+fromUserName);
				boolean group = weixinService.addUserGroup(fromUserName, 0);
				log.info("给无角色打标签结束开始 ：group="+group);
				if(group==false){
					log.info("给无角色打标签失败 ：");
					resMessage.setRetCode(RetCode.FAIL);
					resMessage.setRetMsg("给无角色打标签失败");
				}else{
					log.info("给无角色打标签成功");
					resMessage.setRetCode(RetCode.SUCCESS);
					resMessage.setRetMsg("欢迎关注享云服务");
				}
				return resMessage;
			}
			// 根据主键userId查询用户详情接口
			ReqMessage req2 = ReqMessageUtil.makeSpReq();
			req2.getReqMap().put("userId", res1.getValue("userId").toString());
			log.info("查询用户详情接口开始[【2】【2】【2】【2】 ：req2=" + req2);
			ResMessage res2 = userServiceRemote_sp.getUserByIdSaaS(req2);
			log.info("查询用户详情接口结束【2】【2】【2】【2】 ：res2=" + res2);
			// 判断查询用户详情是否成功
			if (!res2.getRetCode().equals(RetCode.SUCCESS)) {
				log.info("查询用户详情接口失败  ：" + res2.getRetMsg());
				return res2;
			}
			Map<String, Object> map = (Map<String, Object>) res2.getValue("merUser");
			if (map.get("merId") == null || "".equals(map.get("merId"))) {// 未取到商户号
				resMessage.setRetCode(RetCode.FAIL);
				resMessage.setRetMsg("未取到商户号");
				log.info("查询用户详情接口【未取到商户号】 ：" + res2);
				return resMessage;
			}

			if (!"0".equals(map.get("state").toString())) {// 用户不可用
				resMessage.setRetCode(RetCode.FAIL);
				resMessage.setRetMsg("用户不可用号");
				log.info("查询用户详情接口 【用户不可用号】：" + resMessage.getRetMsg());
				return resMessage;
			}
			String mediaId = map.get("merId").toString();// 用户的商户

			// 店铺部署详情接口
			ReqMessage req3 = ReqMessageUtil.makeSpReq();
			req3.getReqMap().put("storeId", mediaId);
			log.info("店铺部署详情接口开始 【4】【4】【4】【4】：req3=" + req3);
			ResMessage res3 = storeInfServiceRemot.getStoreInfByPri(req3);
			log.info("店铺部署详情接口结束【4】【4】【4】【4】 ：res3=" + res3);
			// 获取店铺详情失败
			if (!res3.getRetCode().equals(RetCode.SUCCESS)) {
				log.info("店铺部署详情接口失败  ：" + res3.getRetMsg());
				return res3;
			}
			String rank = map.get("rank").toString();// 角色
			if(rank.equals("1")){
				log.info("进入 ：======您已经是saas收银员了===状态正常=========");
				//给收银员打标签
				log.info("给收银员打标签接口开始 ：fromUserName="+fromUserName);
				boolean group = weixinService.addUserGroup(fromUserName,100);
				log.info("给收银员打标签结束结束 ：grou="+group);
				if(group==false){
					log.info("给收银员打标签失败 ：");
					resMessage.setRetCode(RetCode.FAIL);
					resMessage.setRetMsg("给收银员打标签失败");
					return resMessage;
				}
				//获取店铺信息
				StoreInf storeInf =(StoreInf)res3.getResMap().get("storeInf");
				String storeShortName = storeInf.getStoreShortName();
				resMessage.setRetCode(RetCode.SUCCESS);
				resMessage.setRetMsg("欢迎重新关注享云服务,您已绑定过"+ storeShortName +"收银员.");
				return  resMessage;
			}else if(rank.equals("0")){
				log.info("进入 ：======您已经是saas收款人了===状态正常=========");
				//获取收款人主商户信息
				StoreInf storeInf =(StoreInf)res3.getResMap().get("storeInf");
				String storeId = storeInf.getStoreId();
				Map<String, Object> judgemap = this.judgeReceiver(storeId);
				String retCode = StringUtil.trim(judgemap.get(CommonConsts.RETCODE));
				if(!RetCode.SUCCESS.equals(retCode)){
					resMessage.setRetCode(RetCode.FAIL);
					return resMessage;
				}
				String accountType = StringUtil.trim(judgemap.get(CommonConsts.ACCOUNTTYPE));
				
				if(StringUtil.isNotEmpty(accountType)){
					//给收款人打标签
					boolean group = false;
					log.info("给收款人打标签接口开始 ：fromUserName = "+fromUserName);
					if(ValueConsts.STATE_ONE.equals(accountType)){
						group = weixinService.addUserGroup(fromUserName,103);
						log.info("给个体户收款人打标签结束开始 ：group="+group);
					}else if(ValueConsts.STATE_TWO.equals(accountType)){
						group = weixinService.addUserGroup(fromUserName,101);
						log.info("给小微收款人打标签结束开始 ：group="+group);
					}
					if(group==false){
						log.info("给收款人打标签失败 ");
						resMessage.setRetCode(RetCode.FAIL);
						resMessage.setRetMsg("给收款人打标签失败");
						return resMessage;
					}
					log.info("给收款人打标签成功");
				}
				//通过主商户获取店铺信息
				ReqMessage req5 = ReqMessageUtil.makeSpReq();
				req5.getReqMap().put("merId", storeId);
				req5.getReqMap().put("registerProcsStates","'05','06','07','08','09','10'");
				log.info("店铺部署详情列表接口开始【5】【5】【5】【5】 ：req5=" + req5);
				ResMessage res5 = storeInfServiceRemot.getStoreInfList(req5);
				log.info("店铺部署详情列表接口结束 【5】【5】【5】【5】：res5=" + res5);
				if(!res5.getRetCode().equals(RetCode.SUCCESS)){
					log.info("店铺部署详情列表接口失败 : "+res5.getRetMsg());
					return res5;
				}else if(res5.getValue("totalSize").toString().equals("0")){
					log.info("店铺部署详情列表获取数据失败 : "+res5.getRetMsg());
					res5.setRetCode(RetCode.NO_DATA);
					return res5;
				}else{
					List<StoreInf> list = (List<StoreInf>)res5.getValue("storeInfList");
					StoreInf inf = list.get(0);
					String storeShortName = inf.getStoreShortName();
					resMessage.setRetCode(RetCode.SUCCESS);
					resMessage.setRetMsg("欢迎关注享云服务,您已绑定过"+ storeShortName +"收款人");
					resMessage.put("isPayee", "0");//标记为收款人
					resMessage.put("storeList", list);//店铺列表	
					return  resMessage;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(String.format("==★★★异常，操作失败："), e);
			resMessage.setRetCode(RetCode.FAIL);
		}
		return resMessage;
	}
	
	/**
	 * 获取用户的详情信息、店铺信息、第三方网站信息、绑定第三方网站
	 * @param sceneId       userId扫码参数（用户userID）
	 * @param fromUserName  opneid
	 * @return
	 */
	public ResMessage scanQrcode(String sceneId,String fromUserName){
		
		ResMessage resMessage = new ResMessage();
		try {
		
		//根据主键userId查询用户详情接口
		ReqMessage req2 = ReqMessageUtil.makeSpReq();
		req2.getReqMap().put("userId", sceneId);
		log.info("查询用户详情接口开始【 getUserByIdSaaS】：req2=" + req2);
		 ResMessage res2 = userServiceRemote_sp.getUserByIdSaaS(req2);
		log.info("查询用户详情接口结束 ：res2=" + res2);
		//判断查询用户详情是否成功
		if(!res2.getRetCode().equals(RetCode.SUCCESS)){
			log.info("查询用户详情接口失败  ：" +res2.getRetMsg());
			return res2;
		}
		Map<String,Object> map =(Map<String,Object>)res2.getValue("merUser");
		if(map.get("merId") == null||"".equals(map.get("merId"))){//未取到商户号
			resMessage.setRetCode(RetCode.FAIL);
			resMessage.setRetMsg("未取到商户号");
			log.info("查询用户详情接口 【未取到商户号】："+resMessage.getRetMsg());
			return resMessage;
		}
		
		if(!"0".equals(map.get("state").toString())){//用户不可用
			resMessage.setRetCode(RetCode.FAIL);
			resMessage.setRetMsg("用户不可用号");
			log.info("查询用户详情接口【用户不可用号】 ：" +resMessage.getRetMsg());
			return resMessage;
		}
		String mediaId = map.get("merId").toString();//用户的商户
		String rank = map.get("rank").toString();//角色
		//店铺部署详情接口
		ReqMessage req3 = ReqMessageUtil.makeSpReq();
		req3.getReqMap().put("storeId", mediaId);
		log.info("店铺部署详情接口开始 ：req3=" + req3);
		ResMessage res3 = storeInfServiceRemot.getStoreInfByPri(req3);
		log.info("店铺部署详情接口结束 ：res3=" + res3);
		//获取店铺详情失败
		if(!res3.getRetCode().equals(RetCode.SUCCESS)){
			log.info("店铺部署详情接口失败  ：" +res3.getRetMsg());
			return res3;
		}
		//根据openid查询第三方网站用户的用户编号
		ReqMessage req1 = ReqMessageUtil.makeSpReq();
		req1.getReqMap().put("externaluserId", fromUserName);
		req1.getReqMap().put("state","2");
		log.info("查询第三方网站用户接口开始 ：req1=" + req1);
	    ResMessage res1 = userServiceRemote_sp.queryUserBind(req1);
		log.info("查询第三方网站用户接口结束 ：res1=" + res1);
		//第三方网站查询失败
		if(!res1.getRetCode().equals(RetCode.SUCCESS)&&!res1.getRetCode().equals(RetCode.NO_DATA)){
			log.info("查询第三方网站用户接口失败 : "+res1.getRetMsg());
			return res1;
		}
		
		String trim = StringUtil.trim(res1.getValue("userId"));
		if(!res1.getRetCode().equals(RetCode.NO_DATA)&&!trim.equals(sceneId)){
			log.info("【】【】【】【】【】【】【你已绑定过其他收银员或收款人】【】【】【】【】【】【】"); 
			ResMessage ress=this.existPeople(resMessage,res1,res2,sceneId,fromUserName,rank);
		    return ress;
		}else{
			log.info("【】【】【】【】【】【】【您还没有绑定过,可以进行绑定】【】【】【或】【】【】【】【您已经绑定过此收款人或收银员】"); 
			ResMessage resss=this.emptyPeople(resMessage,res1,res2,res3,sceneId,fromUserName,rank);
		    return resss;
		}
		
		} catch (Exception e) {
			e.printStackTrace();
			log.error(String.format("==★★★异常，操作失败："), e);
			resMessage.setRetCode(RetCode.UNKNOWN);
		}
		return resMessage;
	}
	
	
	public ResMessage existPeople(ResMessage resMessage,ResMessage res1,ResMessage res2,String sceneId,String fromUserName,String rank) throws Exception{
			String string = res1.getValue("userId").toString();
			//根据主键userId查询用户详情接口
			ReqMessage req7 = ReqMessageUtil.makeSpReq();
			req7.getReqMap().put("userId", string);
			log.info("查询用户详情接口开始 ：req7=" + req7);
		    ResMessage res7 = userServiceRemote_sp.getUserByIdSaaS(req7);
			log.info("查询用户详情接口结束 ：resMessage=" + res7);
			//判断查询用户详情是否成功
			if(!res7.getRetCode().equals(RetCode.SUCCESS)){
				log.info("查询用户详情接口失败  ：" +res7.getRetMsg());
				return res7;
			}
			Map<String,Object> map1 =(Map<String,Object>)res7.getValue("merUser");
			if(map1.get("merId") == null||"".equals(map1.get("merId"))){//未取到商户号
				resMessage.setRetCode(RetCode.FAIL);
				resMessage.setRetMsg("未取到商户号");
				log.info("查询用户详情接口 【未取到商户号】："+resMessage.getRetMsg());
				return resMessage;
			}
			if(!"0".equals(map1.get("state").toString())){//用户不可用
				resMessage.setRetCode(RetCode.FAIL);
				resMessage.setRetMsg("用户不可用号");
				log.info("查询用户详情接口【用户不可用号】 ：" +resMessage.getRetMsg());
				return resMessage;
			}
			String mediaId1 = map1.get("merId").toString();//用户的商户
			String rank1 = map1.get("rank").toString();//角色
			//店铺部署详情接口
			ReqMessage req8 = ReqMessageUtil.makeSpReq();
			req8.getReqMap().put("storeId", mediaId1);
			log.info("店铺部署详情接口开始 ：req8=" + req8);
			ResMessage res8 = storeInfServiceRemot.getStoreInfByPri(req8);
			log.info("店铺部署详情接口结束 ：resMessage=" + res8);
			//获取店铺详情失败
			if(!res8.getRetCode().equals(RetCode.SUCCESS)){
				log.info("店铺部署详情接口失败  ：" +res8.getRetMsg());
				return res8;
			}
			if(rank1.equals("1")){//收银员
				log.info("进入 ：======您已经是收银员了===状态正常=========");
				//给收银员打标签
				log.info("给收银员打标签接口开始fromUserName ：="+fromUserName);
				boolean group = weixinService.addUserGroup(fromUserName,100);
				log.info("给收银员打标签接口结束 ：group="+group);
				if(group==false){
					log.info("给收银员打标签失败 ：");
					resMessage.setRetCode(RetCode.FAIL);
					resMessage.setRetMsg("给收银员打标签失败");
					return resMessage;
				}
				//获取店铺信息
				StoreInf storeInf =(StoreInf)res8.getResMap().get("storeInf");
				String storeShortName = storeInf.getStoreShortName();
				resMessage.setRetCode(RetCode.SUCCESS);
				if(rank.equals("1")){
					log.info("进入 ：=====您已绑定过"+ storeShortName +"收银员,(无法再成为收银员).===");
					resMessage.setRetMsg("欢迎关注享云服务,您已绑定过"+ storeShortName +"收银员,(无法再成为收银员).");
					return  resMessage;
				}else{
					log.info("进入 ：======您已绑定过"+ storeShortName +"收银员,(无法再成为它店铺收款人).===");
					resMessage.setRetMsg("欢迎关注享云服务,您已绑定过"+ storeShortName +"收银员,(无法再成为它店铺收款人).");
					return  resMessage;
				}
			}else if(rank1.equals("0")){//收款人
				log.info("进入 ：=======您已经是收款人了===========");
				//获取收款人主商户信息
				StoreInf storeInf =(StoreInf)res8.getResMap().get("storeInf");
				String storeId = storeInf.getStoreId();
				Map<String, Object> judgemap = this.judgeReceiver(storeId);
				String retCode = StringUtil.trim(judgemap.get(CommonConsts.RETCODE));
				if(!RetCode.SUCCESS.equals(retCode)){
					resMessage.setRetCode(RetCode.FAIL);
					return resMessage;
				}
				String accountType = StringUtil.trim(judgemap.get(CommonConsts.ACCOUNTTYPE));
				
				if(StringUtil.isNotEmpty(accountType)){
					//给收款人打标签
					boolean group = false;
					log.info("给收款人打标签接口开始 ：fromUserName = "+fromUserName);
					if(ValueConsts.STATE_ONE.equals(accountType)){
						group = weixinService.addUserGroup(fromUserName,103);
						log.info("给个体户收款人打标签结束开始 ：group="+group);
					}else if(ValueConsts.STATE_TWO.equals(accountType)){
						group = weixinService.addUserGroup(fromUserName,101);
						log.info("给小微收款人打标签结束开始 ：group="+group);
					}
					if(group==false){
						log.info("给收款人打标签失败 ");
						resMessage.setRetCode(RetCode.FAIL);
						resMessage.setRetMsg("给收款人打标签失败");
						return resMessage;
					}
					log.info("给收款人打标签成功");
				}
					log.info("获取的收款人主商户信息 ：===============");
					//通过主商户获取店铺信息
					ReqMessage req5 = ReqMessageUtil.makeSpReq();
					req5.getReqMap().put("merId", storeId);
					req5.getReqMap().put("registerProcsStates","'05','06','07','08','09','10'");
					log.info("店铺部署详情列表接口开始 ：req5=" + req5);
					ResMessage res5 = storeInfServiceRemot.getStoreInfList(req5);
					log.info("店铺部署详情列表接口结束 ：resMessage=" + res5);
					if(!res5.getRetCode().equals(RetCode.SUCCESS)){
						log.info("店铺部署详情列表接口失败 : "+res5.getRetMsg());
						return res5;
					}else if(res5.getValue("totalSize").toString().equals("0")){
						log.info("店铺部署详情列表获取数据失败 : "+res5.getRetMsg());
						res5.setRetCode(RetCode.NO_DATA);
						return res5;
					}else{
						List<StoreInf> list = (List<StoreInf>)res5.getValue("storeInfList");
						StoreInf inf = list.get(0);
						String storeShortName = inf.getStoreShortName();
						resMessage.setRetCode(RetCode.SUCCESS);
						if(rank.equals("1")){
							log.info("进入 ：======您已绑定过"+ storeShortName +"收款人,(无法再成为收银员).===");
							resMessage.setRetMsg("欢迎关注享云服务,您已绑定过"+ storeShortName +"收款人,(无法再成为收银员).");
							return  resMessage;
						}else{
							log.info("进入 ：======您已绑定过"+ storeShortName +"收款人,(无法再成为其他店收款人员).===");
							resMessage.setRetMsg("欢迎关注享云服务,您已绑定过"+ storeShortName +"收款人,(无法再成为其他店收款人员).");
							return  resMessage;
						}
					}
			}
		resMessage.setRetCode(RetCode.FAIL);	
		return  resMessage;
	}
	
	public ResMessage emptyPeople(ResMessage resMessage,ResMessage res1,ResMessage res2,ResMessage res3,String sceneId,String fromUserName,String rank) throws Exception{
	    //获取店铺简称信息
		StoreInf storeInf =(StoreInf)res3.getResMap().get("storeInf");
		//String trim = StringUtil.trim(res1.getValue("userId"));
		if(rank.equals("1")){
			if(res1.getRetCode().equals(RetCode.NO_DATA)){
				log.info("进入 ：====此收银员还没有绑定过,可以进行绑定此收银员==========");
				
				//根据userId查询第三方网站用户的openid
				ReqMessage req10 = ReqMessageUtil.makeSpReq();
				req10.getReqMap().put("userId", sceneId);
				req10.getReqMap().put("state","2");
				log.info("查询第三方网站用户接口开始 ：req10=" + req10);
			    ResMessage res10 = userServiceRemote_sp.queryUserBind(req10);
				log.info("查询第三方网站用户接口结束 ：resMessage=" + res10);
				//第三方网站查询失败
				if(!res10.getRetCode().equals(RetCode.SUCCESS)&&!res10.getRetCode().equals(RetCode.NO_DATA)){
					log.info("查询第三方网站用户接口失败 : "+res10.getRetMsg());
					return res10;
				}
				if(res10.getRetCode().equals(RetCode.NO_DATA)){
					log.info("进入 ：====您还没有绑定过收银员,可以进行绑定收银员==========");
					//给收银员打标签
					log.info("给收银员打标签接口开始 fromUserName=："+fromUserName);
					//测试数据+++++++++++++++++++++++++
					//fromUserName="o9Gdj1Z89rbDTqeWZN5NCCbPR00c";
					boolean group = weixinService.addUserGroup(fromUserName,100);
					log.info("给收银员打标签接口结束 ：group="+group);
					if(group==false){
						log.info("给收银员打标签失败 ：");
						resMessage.setRetCode(RetCode.FAIL);
						resMessage.setRetMsg("给收银员打标签失败");
						return resMessage;
					}
					//根据userId查询第三方网站用户的openid
					ReqMessage req7 = ReqMessageUtil.makeSpReq();
					req7.getReqMap().put("userId",sceneId);
					req7.getReqMap().put("externaluserId",fromUserName);
					req7.getReqMap().put("state","4");
					log.info("查询第三方网站用户接口开始 ：req7=" + req7);
				    ResMessage res7 = userServiceRemote_sp.queryUserBind(req7);
					log.info("查询第三方网站用户接口结束 ：resMessage=" + res7);
					//第三方网站查询失败
					if(!res7.getRetCode().equals(RetCode.SUCCESS)&&!res7.getRetCode().equals(RetCode.NO_DATA)){
						log.info("查询第三方网站用户接口失败 : "+res7.getRetMsg());
						return res7;
					}
					
					if(res7.getRetCode().equals(RetCode.NO_DATA)){
						log.info("进入 ：=====【进行增加绑定】==");
						ReqMessage req4 = ReqMessageUtil.makeSpReq();
						req4.getReqMap().put("externaluserId", fromUserName);
						req4.getReqMap().put("userId",sceneId);
						req4.getReqMap().put("externalWeb","wx");
						log.info("绑定第三方网站用户接口开始 ：req4 = " +  req4);
						ResMessage res4 = userServiceRemote_sp.bindUser(req4);
						log.info("绑定第三方网站用户接口结束 ：ressage="+res4);
						if(!res4.getRetCode().equals(RetCode.SUCCESS)){
							log.info("绑定第三方网站用户接口失败 : "+res4.getRetMsg());
							return res4;
						}
						String storeShortName = storeInf.getStoreShortName();
						resMessage.setRetCode(RetCode.SUCCESS);
						resMessage.setRetMsg("欢迎关注享云服务,您已成功绑定"+ storeShortName +"收银员");
						return  resMessage;
					}else{
						log.info("进入 ：====【进行重新绑定】====");
						log.info("给收银员打标签成功 ：");
						ReqMessage req5 = ReqMessageUtil.makeSpReq();
						req5.getReqMap().put("externaluserId", fromUserName);
						req5.getReqMap().put("userId",sceneId);
						req5.getReqMap().put("state","2");
						log.info("绑定第三方网站用户接口开始unBindUser ：req5=" + req5);
						ResMessage res5 = userServiceRemote_sp.unBindUser(req5);
						log.info("绑定第三方网站用户接口结束 ：resage=" +res5);
						if(!res5.getRetCode().equals(RetCode.SUCCESS)){
							log.info("绑定第三方网站用户接口失败 : "+res5.getRetMsg());
							return res5;
						}
						//获取店铺简称
						String storeShortName = storeInf.getStoreShortName();
						resMessage.setRetCode(RetCode.SUCCESS);
						resMessage.setRetMsg("欢迎关注享云服务,您又重新绑定"+ storeShortName +"收银员");
						return  resMessage;
					}
				}else{
					log.info("进入 ：====此收银员已被人绑定(无法绑定)===========");
					resMessage.setRetCode(RetCode.SUCCESS);
					resMessage.setRetMsg("欢迎关注享云服务,此码已被人绑定(无法绑定)");
					return resMessage;
				}	
			}else{
				log.info("【	进入】【】【】【您已经绑定过此收银员】"); 
				//给收银员打标签
				log.info("给收银员打标签接口开始 ：fromUserName="+fromUserName);
				boolean group = weixinService.addUserGroup(fromUserName,100);
				log.info("给收银员打标签接口结束 ：group="+group);
				if(group==false){
					log.info("给收银员打标签失败 ：");
					resMessage.setRetCode(RetCode.FAIL);
					resMessage.setRetMsg("给收银员打标签失败");
					return resMessage;
				}
				//获取店铺简称
				String storeShortName = storeInf.getStoreShortName();
				resMessage.setRetCode(RetCode.SUCCESS);
				resMessage.setRetMsg("欢迎关注享云服务,您已成功绑定过"+ storeShortName +"收银员(无需在绑定)");
				return  resMessage;
			}
				
		}else{
			//获取收款人主商户信息
			String storeId = storeInf.getStoreId();
			//通过主商户获取店铺信息
			ReqMessage req5 = ReqMessageUtil.makeSpReq();
			req5.getReqMap().put("merId", storeId);
			req5.getReqMap().put("registerProcsStates","'05','06','07','08','09','10'");
			log.info("店铺部署详情列表接口开始 ：req5=" + req5);
			ResMessage res5 = storeInfServiceRemot.getStoreInfList(req5);
			log.info("店铺部署详情列表接口结束 ：resMessage=" + res5);
			if(!res5.getRetCode().equals(RetCode.SUCCESS)){
				log.info("店铺部署详情列表接口失败 : "+res5.getRetMsg());
				return res5;
			}else if(res5.getValue("totalSize").toString().equals("0")){
				log.info("店铺部署详情列表获取数据失败 : "+res5.getRetMsg());
				res5.setRetCode(RetCode.NO_DATA);
				return res5;
			}
			List<StoreInf> list = (List<StoreInf>)res5.getValue("storeInfList");
				
			StoreInf inf = list.get(0);
			String storeShortName = inf.getStoreShortName();
			if(res1.getRetCode().equals(RetCode.NO_DATA)){
				log.info("进入 ：====此收款人还没有绑定过,可以进行绑定此收款人==========");
				//根据userId查询第三方网站用户的openid
				ReqMessage req7 = ReqMessageUtil.makeSpReq();
				req7.getReqMap().put("userId", sceneId);
				req7.getReqMap().put("state","2");
				log.info("查询第三方网站用户接口开始 ：req7=" + req7);
			    ResMessage res7 = userServiceRemote_sp.queryUserBind(req7);
				log.info("查询第三方网站用户接口结束 ：resMessage=" + res7);
				//第三方网站查询失败
				if(!res7.getRetCode().equals(RetCode.SUCCESS)&&!res7.getRetCode().equals(RetCode.NO_DATA)){
					log.info("查询第三方网站用户接口失败 : "+res7.getRetMsg());
					return res7;
				}
				if(res7.getRetCode().equals(RetCode.NO_DATA)){
					log.info("进入 ：====您还没有绑定过收款人,可以进行绑定收款人==========");
					//根据userId查询第三方网站用户的openid
					ReqMessage req6 = ReqMessageUtil.makeSpReq();
					req6.getReqMap().put("userId", sceneId);
					req6.getReqMap().put("externaluserId", fromUserName);
					req6.getReqMap().put("state","4");
					log.info("查询第三方网站用户接口开始 ：req6=" + req6);
				    ResMessage res6 = userServiceRemote_sp.queryUserBind(req6);
					log.info("查询第三方网站用户接口结束 ：resMessage=" + res6);
					//第三方网站查询失败
					if(!res6.getRetCode().equals(RetCode.SUCCESS)&&!res6.getRetCode().equals(RetCode.NO_DATA)){
						log.info("查询第三方网站用户接口失败 : "+res6.getRetMsg());
						return res6;
					}
					
					Map<String, Object> judgemap = this.judgeReceiver(storeId);
					String retCode = StringUtil.trim(judgemap.get(CommonConsts.RETCODE));
					if(!RetCode.SUCCESS.equals(retCode)){
						resMessage.setRetCode(RetCode.FAIL);
						return resMessage;
					}
					String accountType = StringUtil.trim(judgemap.get(CommonConsts.ACCOUNTTYPE));
					
					if(StringUtil.isNotEmpty(accountType)){
						//给收款人打标签
						boolean group = false;
						log.info("给收款人打标签接口开始 ：fromUserName = "+fromUserName);
						if(ValueConsts.STATE_ONE.equals(accountType)){
							group = weixinService.addUserGroup(fromUserName,103);
							log.info("给个体户收款人打标签结束开始 ：group="+group);
						}else if(ValueConsts.STATE_TWO.equals(accountType)){
							group = weixinService.addUserGroup(fromUserName,101);
							log.info("给小微收款人打标签结束开始 ：group="+group);
						}
						if(group==false){
							log.info("给收款人打标签失败 ");
							resMessage.setRetCode(RetCode.FAIL);
							resMessage.setRetMsg("给收款人打标签失败");
							return resMessage;
						}
						log.info("给收款人打标签成功");
					}
				
					for (StoreInf storeInf2 : list) {
						//店铺状态
						String registerProcsState = storeInf2.getRegisterProcsState();
						int parseInt = Integer.parseInt(registerProcsState);
						
						if(parseInt==05){
							log.info("店铺为未邀请状态 ：=======++++++====改为未签约状态===++++");
							//修改商户店铺详细信息接口(改为未签约状态)
							ReqMessage req9 = ReqMessageUtil.makeSpReq();
							storeInf2.setRegisterProcsState("10");
							storeInf2.setIntime(null);
							storeInf2.setModtime(null);
							Map<String, String> rmap = SaasPropertyUtil.javaBeanToMap(storeInf2);
							req9.putAll(rmap);
							log.info("修改商户店铺详细信息接口开始 ：【3】【3】【3】【3】req9=" +req9);
							ResMessage res9 = storeInfServiceRemot.updateStoreInf(req9);
							log.info("修改商户店铺详细信息接口结束 ：【3】【3】【3】【3】resMessage=" + res9);
							//修改商户店铺失败
							if(!res9.getRetCode().equals(RetCode.SUCCESS)){
								resMessage.setRetCode(RetCode.FAIL);
								resMessage.setRetMsg("修改商户店铺失败");
								log.info("修改商户店铺接口失败  ：【res9】【失败】" +res9.getRetMsg());
								return resMessage;
							}
						}	
					}
					if(res6.getRetCode().equals(RetCode.NO_DATA)){
						log.info("进入 ：======新增绑定====");
						ReqMessage req4 = ReqMessageUtil.makeSpReq();
						req4.getReqMap().put("externaluserId", fromUserName);
						req4.getReqMap().put("userId",sceneId);
						req4.getReqMap().put("externalWeb","wx");
						log.info("绑定第三方网站用户接口开始 ：bindUser  " +  req4);
						ResMessage res4 = userServiceRemote_sp.bindUser(req4);
						log.info("绑定第三方网站用户接口结束 ：ressage="+res4);
						if(!res4.getRetCode().equals(RetCode.SUCCESS)){
							log.info("绑定第三方网站用户接口失败 : "+res4.getRetMsg());
							return res4;
						}
						resMessage.setRetCode(RetCode.SUCCESS);
						resMessage.setRetMsg("欢迎使用享云服务，您已绑定"+ storeShortName +"收款人，请点击底部收入结算按钮进行签约操作。若未出现请稍等1分钟或退出公众号再次进入。");
						resMessage.put("isPayee", "0");//标记为收款人
						resMessage.put("storeList", list);//店铺列表
						return  resMessage;
					}else{
						log.info("进入 ：===进行修改绑定====");
						ReqMessage req8 = ReqMessageUtil.makeSpReq();
						req8.getReqMap().put("externaluserId", fromUserName);
						req8.getReqMap().put("userId",sceneId);
						req8.getReqMap().put("state","2");
						log.info("绑定第三方网站用户接口开始unBindUser ：req8=" + req8);
						ResMessage res8 = userServiceRemote_sp.unBindUser(req8);
						log.info("绑定第三方网站用户接口结束 ：resage=" +res8);
						if(!res8.getRetCode().equals(RetCode.SUCCESS)){
							log.info("绑定第三方网站用户接口失败 : "+res8.getRetMsg());
							return res8;
						}
						//获取店铺简称
						resMessage.setRetCode(RetCode.SUCCESS);
						resMessage.setRetMsg("欢迎使用享云服务，您已绑定"+ storeShortName +"收款人，请点击底部收入结算按钮进行签约操作。若未出现请稍等1分钟或退出公众号再次进入。");
						resMessage.put("isPayee", "0");//标记为收款人
						resMessage.put("storeList", list);//店铺列表
						return  resMessage;
					}
					
				}else{
					log.info("进入 ：====此收款人已被人绑定了===========");
					resMessage.setRetCode(RetCode.SUCCESS);
					resMessage.setRetMsg("欢迎关注享云服务,此店铺已被人绑定了,你无法成为"+ storeShortName +"店的收款人");
					return  resMessage;
				}
			}else{
				log.info("【	进入】【】【】【您已成功绑定过"+ storeShortName +"收款人(无需在绑定)】"); 
				Map<String, Object> judgemap = this.judgeReceiver(storeId);
				String retCode = StringUtil.trim(judgemap.get(CommonConsts.RETCODE));
				if(!RetCode.SUCCESS.equals(retCode)){
					resMessage.setRetCode(RetCode.FAIL);
					return resMessage;
				}
				String accountType = StringUtil.trim(judgemap.get(CommonConsts.ACCOUNTTYPE));
				
				if(StringUtil.isNotEmpty(accountType)){
					//给收款人打标签
					boolean group = false;
					log.info("给收款人打标签接口开始 ：fromUserName = "+fromUserName);
					if(ValueConsts.STATE_ONE.equals(accountType)){
						group = weixinService.addUserGroup(fromUserName,103);
						log.info("给个体户收款人打标签结束开始 ：group="+group);
					}else if(ValueConsts.STATE_TWO.equals(accountType)){
						group = weixinService.addUserGroup(fromUserName,101);
						log.info("给小微收款人打标签结束开始 ：group="+group);
					}
					if(group==false){
						log.info("给收款人打标签失败 ");
						resMessage.setRetCode(RetCode.FAIL);
						resMessage.setRetMsg("给收款人打标签失败");
						return resMessage;
					}
					log.info("给收款人打标签成功");
				}
				resMessage.setRetCode(RetCode.SUCCESS);
				resMessage.setRetMsg("欢迎使用享云服务，您已绑定"+ storeShortName +"收款人，请点击底部收入结算按钮进行签约操作。若未出现请稍等1分钟或退出公众号再次进入。");
				resMessage.put("isPayee", "0");//标记为收款人
				resMessage.put("storeList", list);//店铺列表
				return  resMessage;

			}	
		}
    }

	/**
	 * 判断此收款人是否有小微
	 * @param storeId
	 * @return
	 */
	public Map<String,Object> judgeReceiver(String storeId){
	    
	    Map<String,Object> map=new HashMap<String, Object>();
	    //通过主商户获取店铺信息
		ReqMessage reqJudge = ReqMessageUtil.makeSpReq();
		reqJudge.getReqMap().put("merId", storeId);
		log.info("店铺部署详情列表接口开始 ：reqJudge=" + reqJudge);
		ResMessage resJudge = storeInfServiceRemot.getStoreInfList(reqJudge);
		log.info("店铺部署详情列表接口结束 ：resJudge=" + resJudge);
		if(!RetCode.SUCCESS.equals(resJudge.getRetCode())){
			log.info("店铺部署详情列表接口失败 ");
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			return map;
		}else if(ValueConsts.FLAG_ZERO.equals(resJudge.getValue(CommonConsts.TOTAL_SIZE).toString())){
			log.info("店铺部署详情列表获取数据失败 ");
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			return map;
		}
			
		@SuppressWarnings("unchecked")
		List<StoreInf> listt = (List<StoreInf>)resJudge.getValue(CommonConsts.STOREINF_LIST);
		for (StoreInf storeInf : listt) {
			String storeType = storeInf.getStoreType();
			if(ValueConsts.STATE_ZERO.equals(storeType)){
				log.info("店铺部署详情列表中有小微商户");
				map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
				map.put(CommonConsts.ACCOUNTTYPE,ValueConsts.STATE_TWO);//有小微商户
			    return map;
			}
		}
		map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
		map.put(CommonConsts.ACCOUNTTYPE,ValueConsts.STATE_ONE);//全是个体户
		return map;
	}
	
	
	/**
	 * 获取AccessToken
	 * @return
	 */
	@RequestMapping(value="/getAccessToken",produces="text/html;charset=UTF-8")
	@ResponseBody
	public Object getAccessToken(String appId,String secret) {
		AccessTokenPojo accessToken = weixinService.getAccessToken();
		ResMessage resMessage = new ResMessage();
		if(!"".equals(accessToken)){
			resMessage.setRetCode("0000");
			resMessage.setRetMsg("获取AccessToken成功");
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("accessToken", accessToken.getAccessToken());
			resMessage.setResMap(map);
			return JSONObject.fromObject(resMessage).toString();
		}
		resMessage.setRetCode(RetCode.FAIL);
		resMessage.setRetMsg("获取AccessToken失败");
		return  JSONObject.fromObject(resMessage).toString();
	}

	/**
	 * 生成临时二维码
	 * @return
	 */
	@RequestMapping(value="/getTicket",produces="text/html;charset=UTF-8")
	@ResponseBody
	public Object createTemporaryQrCode(String expireSeconds,Integer scene_id) {
		
		String qrCode = weixinService.getTicketQrCode(expireSeconds,scene_id);
		ResMessage resMessage = new ResMessage();
		if(!"".equals(qrCode)){
			resMessage.setRetCode("0000");
			resMessage.setRetMsg("生成临时二维码成功");
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("qrCode", qrCode);
			resMessage.setResMap(map);
			return JSONObject.fromObject(resMessage).toString();
		}
		resMessage.setRetCode(RetCode.FAIL);
		resMessage.setRetMsg("生成临时二维码失败");
		return  JSONObject.fromObject(resMessage).toString();
	}

	/**
	 * 生成永久二维码
	 * @return
	 */
	@RequestMapping(value="/getTickets",produces="text/html;charset=UTF-8")
	@ResponseBody
	public Object createTemporaryQrCode1(String scene_id) {
		
		String qrCode = weixinService.getTicketsQrCode(scene_id);
		ResMessage resMessage = new ResMessage();
		if(!"".equals(qrCode)){
			resMessage.setRetCode("0000");
			resMessage.setRetMsg("生成永久二维码成功");
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("qrCode", qrCode);
			resMessage.setResMap(map);
			return JSONObject.fromObject(resMessage).toString();
		}
		resMessage.setRetCode(RetCode.FAIL);
		resMessage.setRetMsg("生成永久二维码失败");
		return  JSONObject.fromObject(resMessage).toString();
	}
	
	/**
	 *获取自定义菜单 
	 */
	@RequestMapping(value="/getCustomMenu",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getCustomMenu() {
		String menu = weixinService.demandMenu();
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("menu", menu);
		return JSONObject.fromObject(map).toString();
		
	}
	
	/**
	 *创建自定义菜单 
	 */
	@RequestMapping(value="/createMenu2",produces="text/html;charset=UTF-8")
	@ResponseBody
	public Object createMenu2() {
		
		boolean group = weixinService.createMenu2();
		ResMessage resMessage = new ResMessage();
		if(group){
			resMessage.setRetCode("0000");
			resMessage.setRetMsg("创建自定义菜单 成功");
			return JSONObject.fromObject(resMessage).toString();
		}
		resMessage.setRetCode(RetCode.FAIL);
		resMessage.setRetMsg("创建自定义菜单 失败");
		return  JSONObject.fromObject(resMessage).toString();
	}
	
	/**
	 *创建个性化菜单 （收银员）
	 */
	@RequestMapping(value="/createMenu",produces="text/html;charset=UTF-8")
	@ResponseBody
	public Object createMenu() {
		
		boolean group = weixinService.createMenu();
		ResMessage resMessage = new ResMessage();
		if(group){
			resMessage.setRetCode("0000");
			resMessage.setRetMsg("创建个性化菜单成功收银员");
			return JSONObject.fromObject(resMessage).toString();
		}
		resMessage.setRetCode(RetCode.FAIL);
		resMessage.setRetMsg("创建个性化菜单失败收银员");
		return  JSONObject.fromObject(resMessage).toString();
	}
	/**
	 *创建个性化菜单 1（收款人）
	 */
	@RequestMapping(value="/createMenu1",produces="text/html;charset=UTF-8")
	@ResponseBody
	public Object createMenu1() {
	
		boolean group = weixinService.createMenu1();
		ResMessage resMessage = new ResMessage();
		if(group){
			resMessage.setRetCode("0000");
			resMessage.setRetMsg("创建个性化菜单成功收款人");
			return JSONObject.fromObject(resMessage).toString();
		}
		resMessage.setRetCode(RetCode.FAIL);
		resMessage.setRetMsg("创建个性化菜单失败收款人");
		return  JSONObject.fromObject(resMessage).toString();
	}
	
	/**
	 *创建个性化菜单 3（收款人个体户）
	 */
	@RequestMapping(value="/createMenu3",produces="text/html;charset=UTF-8")
	@ResponseBody
	public Object createMenu3() {
	
		boolean group = weixinService.createMenu3();
		ResMessage resMessage = new ResMessage();
		if(group){
			resMessage.setRetCode("0000");
			resMessage.setRetMsg("创建个性化菜单成功收款人个体户");
			return JSONObject.fromObject(resMessage).toString();
		}
		resMessage.setRetCode(RetCode.FAIL);
		resMessage.setRetMsg("创建个性化菜单失败收款人个体户");
		return  JSONObject.fromObject(resMessage).toString();
	}
	
	/**
	 *删除菜单 
	 */
    @RequestMapping(value="/deleteMenu",produces="text/html;charset=UTF-8")
	@ResponseBody
	public Object deleteMenu() {
	
		boolean group = weixinService.deleteMenu();
		ResMessage resMessage = new ResMessage();
		if(group){
			resMessage.setRetCode("0000");
			resMessage.setRetMsg("删除菜单成功");
			return JSONObject.fromObject(resMessage).toString();
		}
		resMessage.setRetCode(RetCode.FAIL);
		resMessage.setRetMsg("删除菜单失败");
		return  JSONObject.fromObject(resMessage).toString();
	}
	
    
	/**
	 *删除个性化菜单 
	 */
    @RequestMapping(value="/delconditionalMenu",produces="text/html;charset=UTF-8")
	@ResponseBody
	public Object delconditionalMenu(String menuid) {
	
		boolean group = weixinService.delconditionalMenu(menuid);
		ResMessage resMessage = new ResMessage();
		if(group){
			resMessage.setRetCode("0000");
			resMessage.setRetMsg("删除个性化菜单成功");
			return JSONObject.fromObject(resMessage).toString();
		}
		resMessage.setRetCode(RetCode.FAIL);
		resMessage.setRetMsg("删除个性化菜单失败");
		return  JSONObject.fromObject(resMessage).toString();
	}
	
	/**
	 * 给用户打标签
	 */
	@RequestMapping(value="/addUserGroup",produces="text/html;charset=UTF-8")
	@ResponseBody
	public Object addUserGroup(String openid,Integer to_groupid) {
		boolean group = weixinService.addUserGroup(openid,to_groupid);
		ResMessage resMessage = new ResMessage();
		if(group){
			resMessage.setRetCode("0000");
			resMessage.setRetMsg("用户打标签成功");
			return JSONObject.fromObject(resMessage).toString();
		}
		resMessage.setRetCode(RetCode.FAIL);
		resMessage.setRetMsg("用户打标签失败");
		return  JSONObject.fromObject(resMessage).toString();
	}
	
	/**
	 *添加客服帐号
	 */
	@RequestMapping(value="/addCustomer",produces="text/html;charset=UTF-8")
	@ResponseBody
	public Object addCustomer(String kf_account,String nickname,String password) {
		boolean group = weixinService.addCustomer(kf_account, nickname,password);
		ResMessage resMessage = new ResMessage();
		if(group){
			resMessage.setRetCode("0000");
			resMessage.setRetMsg("添加客服帐号成功");
			return JSONObject.fromObject(resMessage).toString();
		}
		resMessage.setRetCode(RetCode.FAIL);
		resMessage.setRetMsg("添加客服帐号失败");
		return  JSONObject.fromObject(resMessage).toString();
				
	}
	
	/**
	 * 发送客服消息
	 * @param accessToken
	 * @param sceneStr
	 * @return
	 */
	@RequestMapping(value="/sendMessage",produces="text/html;charset=UTF-8")
	@ResponseBody
	public Object sendMessage(String text,String openid) {
		
		boolean message = weixinService.sendMessage(openid,text);
		
		ResMessage resMessage = new ResMessage();
		if(message){
			resMessage.setRetCode("0000");
			resMessage.setRetMsg("发送客服消息成功");
			return JSONObject.fromObject(resMessage).toString();
		}
		resMessage.setRetCode(RetCode.FAIL);
		resMessage.setRetMsg("发送客服消息失败");
		return  JSONObject.fromObject(resMessage).toString();
	}
	
	/**
	 * 获得模板ID
	 * @param accessToken
	 * @param sceneStr
	 * @return
	 */
	@RequestMapping(value="/getIndustry",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getIndustry() {
		
		String message = weixinService.getIndustry();
		
		ResMessage resMessage = new ResMessage();
		if(!"".equals(message)){
			resMessage.setRetCode("0000");
			resMessage.setRetMsg("发送客服消息成功");
			return JSONObject.fromObject(resMessage).toString();
		}
		resMessage.setRetCode(RetCode.FAIL);
		resMessage.setRetMsg("发送客服消息失败");
		return  JSONObject.fromObject(resMessage).toString();
	}
	
	/**
	 * 发送模板消息
	 * @param openid接收者openid
	 * @param template_id模板ID
	 * @param url模板跳转链接
	 * @param amount金额
	 * @param payTime支付时间
	 * @param payType支付类型
	 * @return
	 */
	@RequestMapping(value="/sendTemplateMessage",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String sendTemplateMessage(Map<String,String> map) {
		
		boolean flag = weixinService.sendTemplateMessage1(map);
		
		ResMessage resMessage = new ResMessage();
		if(flag){
			resMessage.setRetCode("0000");
			resMessage.setRetMsg("发送模板消息成功");
			return JSONObject.fromObject(resMessage).toString();
		}
		resMessage.setRetCode(RetCode.FAIL);
		resMessage.setRetMsg("发送模板消息失败");
		return  JSONObject.fromObject(resMessage).toString();
	}
	
	/**
	 * 创建分组
	 * @param groupName
	 * @return
	 */
	@RequestMapping(value="/createGroup",produces="text/html;charset=UTF-8")
	@ResponseBody
	public  String createGroup(String groupName) {
		Map<String,Object> map = weixinService.createGroup(groupName);
		return JSONObject.fromObject(map).toString();
	}
	
	/**
	 * 所有分组
	 * @return
	 */
	@RequestMapping(value="/getGroup",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getGroup() {
		Map<String, Object> map = weixinService.getGroup();
		return JSONObject.fromObject(map).toString();
	}
	
	/**
	 * 删除分组
	 * @return
	 */
	@RequestMapping(value="/deleteGroup",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String deleteGroup(Integer id) {
		Map<String, Object> map = weixinService.deleteGroup(id);
		return JSONObject.fromObject(map).toString();
	}
	
	/**
	 * 用户所属分组
	 * @return
	 */
	@RequestMapping(value="/getUserGroup",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getUserGroup(String openId) {
		Map<String, Object> map = weixinService.getUserGroup(openId);
		return JSONObject.fromObject(map).toString();
	}
	
	/**
	 * 个体商户打标签
	 * @return
	 */
	@RequestMapping(value="/updateGroup",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String updateGroup(String storeId) {
		Map<String,Object> map=new HashMap<String, Object>();
		//通过主商户获取店铺信息
		ReqMessage req = ReqMessageUtil.makeSpReq();
		if(StringUtil.isNotEmpty(storeId)){
			req.getReqMap().put(CommonConsts.STOREID,storeId);
		}
		log.info("店铺部署详情列表接口开始：req=" + req);
		ResMessage res = storeInfServiceRemot.getStoreInfList(req);
		log.info("店铺部署详情列表接口结束 ：res=" + res);
		if(!RetCode.SUCCESS.equals(res.getRetCode())){
			log.info("店铺部署详情列表接口失败 ");
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			map.put(CommonConsts.RETMSG,"店铺部署详情列表接口失败 ");
			return  JSONObject.fromObject(map).toString();
		}else if(ValueConsts.FLAG_ZERO.equals(res.getValue(CommonConsts.TOTAL_SIZE).toString())){
			log.info("店铺部署详情列表获取数据失败 ");
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			map.put(CommonConsts.RETMSG,"查询店铺列表为空");
			return  JSONObject.fromObject(map).toString();
		}
		@SuppressWarnings("unchecked")
		List<StoreInf> list = (List<StoreInf>)res.getValue(CommonConsts.STORE_INF_LIST);
		for (StoreInf storeInf : list) {
			String merId = storeInf.getMerId();
			if(StringUtil.isNotEmpty(merId)){
				continue;
			}
			String stor = storeInf.getStoreId();
			//通过主商户获取店铺信息
			ReqMessage reqM = ReqMessageUtil.makeSpReq();
			reqM.getReqMap().put("merId",stor);
			log.info("店铺部署详情列表接口开始：req=" + reqM);
			ResMessage resM = storeInfServiceRemot.getStoreInfList(reqM);
			log.info("店铺部署详情列表接口结束 ：res=" + resM);
			if(!RetCode.SUCCESS.equals(resM.getRetCode())){
				log.info("店铺部署详情列表接口失败 ");
				map.put(CommonConsts.RETCODE,RetCode.FAIL);
				map.put(CommonConsts.RETMSG,"店铺部署详情列表接口失败 ");
				return  JSONObject.fromObject(map).toString();
			}else if(ValueConsts.FLAG_ZERO.equals(resM.getValue(CommonConsts.TOTAL_SIZE).toString())){
				log.info("店铺部署详情列表获取数据失败 : "+resM.getRetMsg());
				map.put(CommonConsts.RETCODE,RetCode.FAIL);
				map.put(CommonConsts.RETMSG,"查询店铺列表为空");
				continue;
			}
			@SuppressWarnings("unchecked")
			List<StoreInf> listt = (List<StoreInf>)resM.getValue(CommonConsts.STORE_INF_LIST);
			Boolean flag=false;
			for (StoreInf storeInfTwo : listt) {
				String storeType = storeInfTwo.getStoreType();
				if(ValueConsts.STATE_ZERO.equals(storeType)){//有小微
					flag=true;
					break;
				}
			}
			if(flag){
				continue;
			}
			//用户列表查询(此店铺下的收款人)
			ReqMessage reqMe = ReqMessageUtil.makeSpReq();
			reqMe.getReqMap().put(CommonConsts.MERFLAG, stor);
			reqMe.getReqMap().put(CommonConsts.STATE,ValueConsts.USER_NOMAL);
			reqMe.put(CommonConsts.CURRENT_PAGE, String.valueOf(1));
			reqMe.put(CommonConsts.PAGE_SIZE, String.valueOf(100));
			log.info("用户列表查询接口开始 reqMe==="+reqMe);
		    ResMessage resMe = userServiceRemote_sp.queryList(reqMe);
			log.info("用户列表查询接口结束 :resMessage=" + resMe);
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> resultList = (List<Map<String, Object>>)resMe.getResMap().get(CommonConsts.RESULT_LIST);
			//查询出的用户数量
			String totalSize = resMe.getResMap().get(CommonConsts.TOTAL_SIZE).toString();
			if(!ValueConsts.FLAG_ZERO.equals(totalSize)){
				Map<String, Object> objMap = resultList.get(0);
				//查询第三方网站用户接口
				ReqMessage reqMes = ReqMessageUtil.makeSpReq();
				String userId = objMap.get(CommonConsts.USERID).toString();
				reqMes.getReqMap().put(CommonConsts.USERID, userId);
				reqMes.getReqMap().put(CommonConsts.STATE,ValueConsts.EXTERNAL_USER_NOMAL);
				log.info("查询第三方网站用户接口 开始：reqMes = " + reqMes);
				ResMessage resMes = userServiceRemote_sp.queryUserBind(reqMes);
				log.info("查询第三方网站用户接口结束 ：resMessage = " +resMes);
				if(RetCode.SUCCESS.equals(resMes.getRetCode())){
					String openid = resMes.getResMap().get(CommonConsts.EXTERNAL_USER_ID).toString();
					log.info("此商户"+stor+"的openid="+openid);
					Map<String, Object> result = weixinService.getUserGroup(openid);
					log.info("此商户"+stor+"的原标签是="+result);
					if(RetCode.SUCCESS.equals(result.get(CommonConsts.RETCODE))){
						if(StringUtil.isNotEmpty(StringUtil.trim(result.get(CommonConsts.GROUPID)))){
							if(!"103".equals(StringUtil.trim(result.get(CommonConsts.GROUPID)))){
								boolean group = weixinService.addUserGroup(openid,103);
								log.info("给商户"+stor+"重新打标签flag="+group);
							}
						}
					}
				}
			}
		}	
		map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
		return JSONObject.fromObject(map).toString();
	}
	
	
	@RequestMapping("/sen")
	@ResponseBody
	public String sen(String openid,String template_id,String url,String amount,String payTime,String payType) {
		log.info("++++++++++++++++");
		return  JSONObject.fromObject("sss").toString();
	}
	private void sendSignTemplate(String fromUserName, ResMessage resMessage) throws Exception {
		String isPayee = resMessage.getStrValue("isPayee");
		log.info("如果isPayee等于0，就发送待签约模板消息,isPayee="+isPayee);
		if("0".equals(isPayee)){
			String signTemplateId=UmfPropModel.INSTANCE.getPropValue("saas.wx.signTemplateId");
			//立马付产品编号
			//String productId=UmfPropModel.INSTANCE.getPropValue("productId_impay");
			/*if(StringUtil.isEmpty(productId)){
				log.info("获取productId获取失败！");
				return;
			}*/
			//立马付主产品编号
			String mainProductId=UmfPropModel.INSTANCE.getPropValue("mainProductId");
			if(StringUtil.isEmpty(mainProductId)){
				log.info("获取mainProductId获取失败！");
				return;
			}
			// 读取店铺部署详情列表中的店铺列表
			List<StoreInf> list = (List<StoreInf>)resMessage.getValue("storeList");
			for (StoreInf storeInf : list) {
				
				String productId_add = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.PRODUCTID_IMPAY_ADDED);
				String productId = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.PRODUCTID_IMPAY);
				// 渠道开通列表返回查询接口
				ReqMessage req5 = ReqMessageUtil.makeSpReq();
				req5.getReqMap().put("appSysId",storeInf.getStoreId());
				req5.getReqMap().put("productIds","'"+productId+"','"+productId_add+"'");
				log.info("根据主键查询渠道表开始 ：【5】【5】【5】【5】req5 = " + req5);
				ResMessage res5 =appChannelServiceRemote.getAppChannelListByProductids(req5);
				log.info("根据主键查询渠道表结束 ：【5】【5】【5】【5】res5 = " + res5);
				if (res5.getRetCode().equals(RetCode.DB_ERROR)) {
					log.info("查询渠道开通接口失败 ：【res5】【失败】 " + res5.getRetMsg());
				}
				if(res5.getRetCode().equals(RetCode.SUCCESS)){
					//获取查询到的渠道信息
					List<AppChannel> appChannellist = (List<AppChannel>)res5.getValue("appChannelList");
					log.info("appChannellist  "+appChannellist);
					if(appChannellist.size()>0&&appChannellist!=null){
						AppChannel appChannel = appChannellist.get(0);
						//应用编号（店铺id）对应一个主产品号
						if (appChannel.getState().equals(4)) {
							log.info("判断该店铺渠道开通为未签约状态===【】【】=====【】【】=====");
							Integer wecatRates2 = appChannel.getWecatRates();
							double doubleValue3 = wecatRates2.doubleValue();
							double doubleValue4=doubleValue3/1000;
							String wechatRate = String .format("%.3f",doubleValue4)+"%";
							Integer alipayRates2 = appChannel.getAlipayRates();
							double doubleValue = alipayRates2.doubleValue();
							double doubleValue2=doubleValue/1000;
							String alipayRate = String .format("%.3f",doubleValue2)+"%";
							String storeShortName = storeInf.getStoreShortName();//店铺简称
							weixinService.sendSignTemplateMessage(fromUserName, signTemplateId, storeShortName, "支付宝 " + alipayRate, "微信 " + wechatRate);
						}
					}
				}
			}
		}
	}
}
